#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include "tagfs.h"

// get the number of tags from .inode_tagid
int get_num_tag(unsigned int inode)
{
	FILE* fp;
	char system_filepath[256];
	unsigned int size, entry;
	get_system_filepath("/.inode_tagid", system_filepath);
	fp = fopen(system_filepath, "rb");
	if(fp == NULL)
		return -1;
	do
	{
		fread(&size, sizeof(unsigned int), 1, fp);
		fread(&entry, sizeof(unsigned int), 1, fp);
		if(entry == inode)
		{
			fclose(fp);
			return size-2;
		}
	} while(!feof(fp) && !fseek(fp, sizeof(unsigned int) * (size-2), SEEK_CUR));
	fclose(fp);
	return -1;
}

void get_tagid_from_inode(unsigned int inode, unsigned int* tagid)
{
	FILE* fp;
	char system_filepath[256];
	unsigned int size, entry;
	int i;
	get_system_filepath("/.inode_tagid", system_filepath);
	fp = fopen(system_filepath, "rb");
	do
	{
		fread(&size, sizeof(unsigned int), 1, fp);
		fread(&entry, sizeof(unsigned int), 1, fp);
		if(entry == inode)
		{
			for(i=0; i<size-2; i++)
			{
				fread(&tagid[i], sizeof(unsigned int), 1, fp);
			}
			fclose(fp);
			return;
		}
	} while(!feof(fp) && !fseek(fp, sizeof(unsigned int) * (size-2), SEEK_CUR));
	fclose(fp);
}

void get_tagname_list(unsigned int* tagid, char** tag, int num_tag)
{
	FILE* fp;
	struct tagid_name entry;
	char system_filepath[256];
	int i;
	get_system_filepath("/.tagid_tagname", system_filepath);
	for(i=0; i<num_tag; i++)
	{
		fp = fopen(system_filepath, "rb");
		while(!feof(fp))
		{
			fread(&entry, sizeof(struct tagid_name), 1, fp);
			if(entry.id == tagid[i])
			{
				strcpy(tag[i], entry.name);
			}
		}
		fclose(fp);
	}

}

int main(int argc, char *argv[])
{
	FILE* fp;
	int i;
	int num_tag;
	int res;
	char* filename;
	char fullpath[256];
	char** tag;
	unsigned int* tagid;

	filename = argv[1];
	// get the absolute path for the file as it is needed to find its inode number
	getcwd(fullpath, 256);
	strcat(fullpath, "/");
	strcat(fullpath, filename);
	// get file inode
	struct stat *statbuf = (struct stat*)malloc(sizeof(struct stat));
	res = lstat(fullpath, statbuf);
	if(res)
	{
		printf("file does not exist!!!\n");
		return 1;
	}
	num_tag = get_num_tag(statbuf->st_ino);	
	// the inode has no tag
	if(num_tag == -1)
		return 1;
	// allocate tag and tagid
	tag = (char**)malloc(num_tag*sizeof(char*));
	for(i=0; i<num_tag; i++)
		tag[i] = (char*)malloc(256*sizeof(char));
	tagid = (unsigned int*)malloc(num_tag*sizeof(unsigned int));
	// list every tagid
	get_tagid_from_inode(statbuf->st_ino, tagid);
	// convert tagid to file path
	get_tagname_list(tagid, tag, num_tag);
	// print the result
	for(i=0; i<num_tag; i++)
	{
		printf("%s\n", tag[i]);
	}
	return 1;
}
